console.log('cs');
window.cs = new content_script();
let cmdBg = ["post", "get", "ajax", "run","getCookieAll","getCookie","setCookie","removeCookie","RunTool"];

window.SysRunList = [{
    id: '',
    match: '',
    script: [],
    time: new Date().getTime()
}];
//执行js
local.get(listKey).then((list) => {
    if (list && list.length > 0) {
        window.SysRunList = list;
        let url = location.href;
        list.forEach((it, i) => {
            if (it && it.match && new RegExp(it.match).test(url)) {
                //判断是否超时
                if (it.time && new Date().getTime() > it.time) {
                    list[i] = null;
                    return;
                }
                if (typeof it.script === 'string') {
                    if(it.cs){
                        eval(it.script);
                    }else{
                        cs.runJs(it.script);
                    }
                } else if (it.script && it.script.length > 0) {
                    it.script.forEach(x => it.cs?eval(x):cs.runJs(it.script));
                }
            }
        });
        local.set(listKey, SysRunList.filter(x=>x));
    }
});
//--------通讯部分---------//
window.cmd = {
    run_(info, callback) {
        callback(eval(`(${info})()`));
    },
    runAdd:run.add,
    runRemove:run.remove,
    runGet:run.get,
    RunTool_(obj,callback){
        let ret=cs[obj.name](...obj.par);
        callback && callback(ret);
    },
    localGet(key,callback){
        local.get(key).then(callback);
    },
    localSet(obj,callback){
        local.set(obj.key,obj.val).then(callback);
    },
    localRmove(key,callback){
        local.remove(key).then(callback);
    },
    localClear(callback){
        local.clear().then(callback);
    }
};
//开始 id为通讯密钥
window.addEventListener("message", (info) => {
    info = info.data;
    if(info && info.key){
        if (cmdBg.includes(info.key)) {
            chrome.runtime.sendMessage(info, (content) => {
                window.postMessage({
                    cid: info.id,
                    value: content
                }, location.href)
            });
        } else {
            //在当前页寻找处理程序
            Object.keys(cmd).forEach((key) => {
                if (key === info.key) {
                    window.cmd[key](info.value, (content) => {
                        window.postMessage({
                            cid: info.id,
                            value: content
                        }, location.href)
                    });
                }
            });
        }
    }
}, false);

//注入JS
function ij() {
    console.log('ij');
    let cmd = {};
    window.addEventListener('message', (info) => {
        info = info.data;
        if (info.cid) {
            cmd[info.cid] && cmd[info.cid](info.value);
            delete cmd[info.cid];
        }
    });
    function sendContent(key, obj, callback) {
        let id = new Date().getTime();
        cmd[id] = callback;
        //发送信息
        window.postMessage({
            id: id,
            key: key,
            value: obj
        }, location.href);
    }

    let CA = {};
    CA.run = {
        add(obj, callback) {
            if (obj && obj.id && obj.match && obj.script) {
                return sendContent('runAdd',obj, callback)
            }
            console.error('添加缺少参数');
        },
        remove(id, callback) {
            if (id) {
                return sendContent('runRemove',id, callback)
            }
            console.error('请填写唯一标识');
        },
        get(id, callback) {
            if (id) {
                return sendContent('runGet',id, callback)
            }
            console.error('请填写唯一标识');
        }
    };
    CA.cs={
        run(js,callback){
            if (js) {
                return sendContent('run_',js, callback)
            }
        },
        tool(fnName,par,callback){
            sendContent('RunTool_',{
                name:fnName,
                par:par
            },callback)
        }
    };
    CA.bg={
        run(js,callback){
            if (js) {
                return sendContent('run',js, callback)
            }
        },
        post(url, data, callback)  {
            sendContent('post', {
                url,
                data
            }, callback);
        },
        get(url, callback) {
            sendContent('get', url, callback);
        },
        ajax(obj, callback){
            sendContent('ajax', obj, callback);
        },
        tool(fnName,par,callback){
            sendContent('RunTool',{
                name:fnName,
                par:par
            },callback)
        }
    };
    CA.cookie={
        get(obj,callback){
            sendContent("getCookie",obj,callback);
        },
        set(obj,callback){
            sendContent("setCookie",obj,callback);
        },
        getAll(obj,callback){
            sendContent("getCookieAll",obj,callback);
        },
        remove(obj,callback){
            sendContent("removeCookie",obj,callback);
        }
    };
    CA.local={
        get(key,callback){
            sendContent('localGet',key,callback);
        },
        set(key,val,callback){
            sendContent('localSet',{
                key,
                val
            },callback);
        },
        remove(key,callback){
            sendContent('localRmove',key,callback);
        },
        clear(key,callback){
            sendContent('localClear',key,callback);
        }
    };
    //导出函数
    window.CA = CA;

    function handleSend(name,data){
        let event = document.createEvent('HTMLEvents');
        event.initEvent(name, false, true);
        event.data =data;
        window.dispatchEvent(event);
    }
    handleSend('CALoad',CA);
}
cs.runJs(ij);
